#!/usr/bin/groovy
package com.mobtech.ci
import hudson.Util


def kubectlTest() {
    // Test that kubectl can correctly communication with the Kubernetes API
    println "checking kubectl connnectivity to the API"
    sh "kubectl get nodes"

}

def helmDeploy(Map args) {
    def String namespace

    // If namespace isn't parsed into the function set the namespace to the name
    if (args.namespace == null) {
        namespace = args.name
    } else {
        namespace = args.namespace
    }

    // compose set values
    // original version: imageTag=${args.version_tag},replicas=${args.replicas},cpu=${args.cpu},memory=${args.memory},ingress.hostname=${args.hostname}
    helm_set = []
    if (args.set) {
        args.set.each { k, v -> if (v) helm_set << "$k=\"$v\"" }
    }
    set_option = helm_set ? "--set ${helm_set.join(',')}" : ''

    value_files_option = args.value_files? "-f " + args.value_files.join("-f "): ''

    repo_option = args.repo?"--repo ${args.repo}": ''

    version_option = args.version?"--version ${args.version}":''

    if (args.dry_run) {
        println "Running dry-run deployment"

        sh "helm upgrade --reuse-values --dry-run --install ${args.name} ${args.chart_dir} ${value_files_option} ${set_option} ${repo_option} ${version_option} --namespace=${namespace}"
    } else {
        println "Running deployment"

        // reimplement --wait once it works reliable
        sh "helm upgrade --reuse-values --install ${args.name} ${args.chart_dir} ${value_files_option} ${set_option} ${repo_option} ${version_option} --namespace=${namespace}"

        // sleeping until --wait works reliably
        // sleep(20)

        echo "Application ${args.name} successfully deployed. Use helm status ${args.name} to check"
    }
}

def gitEnvVars() {
    // create git envvars
    println "Setting envvars to tag container"

    sh 'git rev-parse HEAD > git_commit_id.txt'
    try {
        env.GIT_COMMIT_ID = readFile('git_commit_id.txt').trim()
        env.GIT_SHA = env.GIT_COMMIT_ID.substring(0, 7)
    } catch (e) {
        error "${e}"
    }
    println "env.GIT_COMMIT_ID ==> ${env.GIT_COMMIT_ID}"

    sh 'git config --get remote.origin.url> git_remote_origin_url.txt'
    try {
        env.GIT_REMOTE_URL = readFile('git_remote_origin_url.txt').trim()
    } catch (e) {
        error "${e}"
    }
    println "env.GIT_REMOTE_URL ==> ${env.GIT_REMOTE_URL}"
}


def sendDingTalkResult() {
    sendDingTalkResultTo("c5c31fbe4f5a3ea02e8d85b362b13626a5a4d38873a12b15333b667b4c79a0a1")
}

// Make sure "HTTP Request" plugin is installed on jenkins master server (https://wiki.jenkins.io/display/JENKINS/HTTP+Request+Plugin)
def sendDingTalkResultTo(token) {
    def build = currentBuild
    def isSuccess = build.result.equals("SUCCESS")
    def duration = Util.getTimeSpanString(build.duration)

    stage('Send DingTalk Result Message') {
        def okTitle= "${build.fullDisplayName} Build Successfully! (${duration})"
        def failTitle= "Failed!! ${build.fullDisplayName} Build (${duration})"
        def title = isSuccess ? okTitle: failTitle
        def content = "Duration: ${duration}"
        def dingTaskUrl = "https://oapi.dingtalk.com/robot/send?access_token=${token}"
        def successPic = "http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png"
        def failurePic = "http://www.iconsdb.com/icons/preview/soylent-red/x-mark-3-xxl.png"
        def link = "${BUILD_URL}/console"
        def msgData = """
            {
                "link": {
                    "title": "${title}",
                    "text": "${content}",
                    "picUrl": "${isSuccess ? successPic : failurePic}",
                    "messageUrl":"${link}"
                },
                "msgtype": "link",
            }
        """
        httpRequest acceptType: 'APPLICATION_JSON', contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: msgData, url: dingTaskUrl
    }
}
